<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\member\model;

use manniu\model\Base;

use think\Db;
use think\Request;

class Member extends Base
{
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    // 只读字段
    protected $readonly = ['username', 'salt', 'regip'];

    // 会员组名称获取器
    protected function getGroupIdNameAttr($value, $data)
    {
        $group_id_name = '暂无会员组';
        $group = MemberGroup::getGroup($data['group_id']);
        if($group){
            $group_id_name = $group->getData('name');
        }
        return $group_id_name;
    }

    // 密码 - 修改器
    protected function setPasswordAttr($value, $data)
    {
        return md5(md5($value) . $data['salt'] . md5($value));
    }

    // 会员组 - 修改器
    protected function setGroupIdAttr($value)
    {
        return $value ? (int)$value : 1;
    }

    /**
     * 模型事件
     */
    protected static function init()
    {
        // 钩子 - 写入后
        Member::afterWrite(function ($member) {
            if (!$member->nickname) {
                Db::name('member')->where('uid','=',$member->uid)->update([
                    'nickname'=>'ssc'.$member->uid.substr(microtime(), 2, 5)
                ]);
            }
        });
    }

    /**
     * 读取会员缓存
     * @param int $uid 用户id
     * @return mixed|null
     */
    public static function getCacheByUid($uid)
    {
        return null;
    }

    /**
     * 更新缓存
     * @param int $uid 用户id
     */
    public static function setCacheByUid($uid)
    {
        return null;
    }

    /**
     * 用户登录认证
     * @param string $username 用户名
     * @param string $password 密码
     * @return integer 登录成功-用户ID，登录失败返0或负整数
     * 返回值:
     * 0 - 表示用户名或密码为空
     * -1 - 表示用户名或密码错误
     * -2 - 表示用户被禁用
     */
    public function login($username = '', $password = '')
    {
        if (!$username || !$password) {
            return 0;
        }
        if (strlen($username) == 11 && is_numeric($username)) { // 判断是否为手机号
            $where['mobile'] = $username;
        } elseif (preg_match('/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/', $username)) { // 匹配正则邮箱
            $where['email'] = $username;
        } else {
            $where['username'] = $username;
        }
        /* 获取用户数据 */
        $member = $this->where($where)->find();
        if ($member) {
            if (md5(md5($password) . $member->getData('salt') . md5($password)) != $member->getData('password')) {
                $this->error = '用户名或密码错误';
                return -1;
            } elseif (0 == $member->getData('status')) {
                $this->error = '您的账户被被禁用，如有疑问请联系客服人员';
                return -2;
            } else {
                // 更新登录信息
                $member->data('last_login_time', time());
                $member->data('last_login_ip', Request::instance()->ip());
                $member->save();
                return $member->uid;
            }
        } else {
            $this->error = '用户名或密码错误';
            return -1;
        }

    }

    /**
     * 注册
     */
    public function register($data, $is_admin = false)
    {
        // 正常注册时，会员初始化信息
        $data['username'] = trim($data['username']);
        $data['password'] = trim($data['password']);
        $data['salt'] = substr(md5(rand(0, 999)), 0, 10);
        $data['nickname'] = isset($data['nickname']) ? trim($data['nickname']) : null;
        $data['mobile'] = isset($data['mobile']) ? trim($data['mobile']) : null;
        $data['email'] = isset($data['email']) ? strtolower($data['email']) : null;
        $data['avatar'] = null;
        $data['chargeable'] = 0;
        $data['read_money'] = 0;
        $data['group_id'] = isset($data['group_id']) && $data['group_id'] != 0 ? (int)$data['group_id'] : 1;
        $data['regip'] = Request::instance()->ip();
        $data['status'] = 1;

        //验证保存会员信息
        $validate = 'add';
        if($is_admin){
            $validate = 'admin_add';
        }
        $result = $this->validate('app\member\validate\Member.'.$validate)->allowField(true)->save($data);
        if (false === $result) {
            // 验证失败 输出错误信息
            return false;
        } else {
            return $this->uid;
        }
    }

    /**
     * 删除会员
     * @param   array $ids 会员uid数组
     */
    public function del($ids)
    {
        $u_ids = [];
        if (is_array($ids)) {
            foreach ($ids as $uid) {
                $u_ids[] = (int)$uid;
            }
        } else {
            $u_ids = (int)$ids;
        }
        $u_ids && self::destroy($u_ids);
    }
}